﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Notifications;
using Raven.Client;
using Topics.Radical.Validation;
using SampleApp.MvcBackend.Data.Model;

namespace SampleApp.MvcBackend.Messaging.Handlers
{
	public class CustomerDenormalizer: Topics.Radical.Messaging.AbstractMessageHandler<CustomerCreated>
	{
		readonly IDocumentStore sessionFactory;

		public CustomerDenormalizer( IDocumentStore sessionFactory )
		{
			Ensure.That( sessionFactory ).Named( () => sessionFactory ).IsNotNull();

			this.sessionFactory = sessionFactory;
		}

		public override void Handle( object sender, CustomerCreated message )
		{
			using ( var session = this.sessionFactory.OpenSession() )
			{
				var id = "views/" + message.AggregateId;

				var current = session.Load<Data.Views.CustomerView>( id );
				if ( current == null )
				{
					current = new Data.Views.CustomerView()
					{
						Id = id,
						CustomerName = message.CustomerName
					};

					session.Store( current );
					session.SaveChanges();
				}
			}
		}
	}
}